#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import time

# API配置
url = "http://172.16.0.8:5005/analyze"
headers = {
    'Content-Type': 'application/json; charset=utf-8'
}

# 测试用例
test_cases = [
    {
        "name": "正常简历测试",
        "data": {
            "resume_text": "张三，软件工程师，5年Java开发经验，熟悉Spring框架。",
            "industry": "technology"
        }
    },
    {
        "name": "金融行业测试",
        "data": {
            "resume_text": "李四，金融分析师，3年银行工作经验，熟悉风险管理。",
            "industry": "finance"
        }
    },
    {
        "name": "长文本测试",
        "data": {
            "resume_text": "王五，高级软件工程师，拥有8年丰富的软件开发经验。精通Java、Python、JavaScript等多种编程语言，熟练掌握Spring Boot、Django、React等主流框架。曾在多家知名互联网公司担任技术负责人，负责大型分布式系统的架构设计和开发。具备扎实的算法基础和系统设计能力，善于解决复杂的技术问题。",
            "industry": "technology"
        }
    },
    {
        "name": "特殊字符测试",
        "data": {
            "resume_text": "赵六，UI/UX设计师，擅长用户体验设计，熟悉Figma、Sketch等工具。",
            "industry": "design"
        }
    }
]

def test_api_case(case):
    print(f"\n{'='*50}")
    print(f"测试用例: {case['name']}")
    print(f"请求数据: {json.dumps(case['data'], ensure_ascii=False)}")
    
    try:
        start_time = time.time()
        response = requests.post(url, json=case['data'], headers=headers, timeout=30)
        end_time = time.time()
        
        print(f"响应时间: {end_time - start_time:.2f}秒")
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            try:
                result = response.json()
                print("✅ 请求成功")
                print(f"匹配度: {result.get('matchScore', 'N/A')}")
                print(f"关键词数量: {len(result.get('keywords', []))}")
                print(f"关键词: {result.get('keywords', [])[:3]}...")  # 只显示前3个
                return True
            except json.JSONDecodeError as e:
                print(f"❌ JSON解析失败: {e}")
                print(f"原始响应: {response.text[:200]}...")
                return False
        else:
            print(f"❌ 请求失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            return False
            
    except requests.exceptions.Timeout:
        print("❌ 请求超时")
        return False
    except requests.exceptions.ConnectionError:
        print("❌ 连接错误")
        return False
    except Exception as e:
        print(f"❌ 未知错误: {e}")
        return False

def main():
    print("开始API诊断测试...")
    print(f"目标URL: {url}")
    
    # 测试服务是否可达
    try:
        response = requests.get("http://172.16.0.8:5005/", timeout=5)
        print(f"✅ 服务可达，状态码: {response.status_code}")
    except:
        print("❌ 服务不可达")
        return
    
    # 运行所有测试用例
    success_count = 0
    total_count = len(test_cases)
    
    for case in test_cases:
        if test_api_case(case):
            success_count += 1
        time.sleep(1)  # 避免请求过于频繁
    
    print(f"\n{'='*50}")
    print(f"测试总结: {success_count}/{total_count} 成功")
    
    if success_count == total_count:
        print("🎉 所有测试通过，API工作正常！")
    elif success_count > 0:
        print("⚠️ 部分测试失败，可能存在间歇性问题")
    else:
        print("❌ 所有测试失败，API存在严重问题")

if __name__ == "__main__":
    main()